/*
 * Create:      柿子
 * CreateDate:  2023/04/30
 * Describe：   左右结构查询导出公共组件 - 视光科门诊患者查询(OptometryOutPatientInquiry) / 角塑订单查询(CornerPlasticOrderQuery) / 角塑销售品类统计(SalesCategoryStatisticsOfCornerPlastic) / 角塑收费查询(CornerPlasticChargesQuery)
 * */
import React, { Component } from 'react';
import { Card, Row, Col, Spin, message, Button } from 'antd';
import { Util } from 'tools';
import { handleExcel } from 'tools/handleExcel';
import store from 'store';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import PublicTablePagination from 'pages/common/PubilcTablePagination';
import GetPatientInformation from 'pages/optometry/component/GetPatientInformation';
import MatchingDetails from 'pages/optometry/glassesManagement/component/MatchingDetails';
import iconListvisits from 'assets/images/icon_listvisits.png';
import iconMessages from 'assets/images/icon_messages.png';
import './style/index.less';

class LeftConditionRightList extends Component {
  constructor(props) {
    super(props);
    let userData = React.$getSessionData();
    this.state = {
      userData,
      categoryData: {},
      selectData: {},
      queryFormData: [],
      page: 1,
      pageSize: 50,
      total: 0,
      loading: false,
      tableData: [],
      totalWidth: 0,
      columns: [],
      rowID: '',
      rowData: {},
      spinLoading: true,
      exportLoading: false,
      totalStatistics: '', // 合计统计
    };
  }

  componentDidMount() {
    let newCategory;
    if ('paras' in this.props && this.props.paras && this.props.paras.params) { // 侧菜单获取类别参数
      newCategory = this.props.paras.params;
    } else {
      if ('location' in this.props && this.props.location.state && this.props.location.state.params) { // 头菜单获取类别参数
        newCategory = this.props.location.state.params;
        React.$setSessionData('LeftConditionRightList', newCategory, false);
      } else { // 头菜单刷新界面时获取类别
        newCategory = React.$getSessionData('LeftConditionRightList', false);
      }
    }
    let categoryData = Util.getObjByUrlStr(newCategory);
    console.log('LeftConditionRightList', categoryData);
    let defaultPageSize = categoryData?.paginationSize === 'small' ? (categoryData?.defaultPageSize || 10) : (categoryData?.defaultPageSize || 50); // 默认条数
    this.setState({ categoryData, pageSize: defaultPageSize }, () => {
      this.getSelectData();
      this.getTableColumns('Y');
    });
  }

  // 组件销毁前将静止让setState修改state的状态
  componentWillUnmount() {
    this.setState = (state, callback) => { return; }
  }

  // 获取下拉框数据
  getSelectData = async () => {
    try {
      let { categoryData, userData } = this.state;
      if (!(categoryData && categoryData.selectCode)) {
        return
      };
      let data = {
        params: [{
          hospID: userData?.hospID || '',
          status: categoryData?.groupType || undefined, // 界面标识
          groupType: categoryData?.groupType || undefined, // 界面标识
          componentName: categoryData?.componentName || undefined, // 组件名
        }]
      }
      let res = await React.$asyncPost(this, categoryData.selectCode, data);
      this.setState({ selectData: res.result });
    } catch (error) {

    }
  }

  // 获取表头数据
  getTableColumns = async (isQuery) => {
    try {
      const { categoryData } = this.state;
      if (!(categoryData && categoryData.componentName)) {
        message.error('列表数据还未配置呢，快去配置先！');
        this.setState({ spinLoading: false });
        return;
      }
      let data = {
        params: [{
          compontName: categoryData.componentName,
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      if (columns && columns.length > 0) {
        this.setState({
          columns,
          totalWidth: res.totalWidth
        })
      }
      let nFormData = res.result?.formData || [];
      this.setState({ queryFormData: nFormData, spinLoading: false }, () => {
        if (isQuery === 'Y') { // 自动查询标志
          // 解决开单日期|取镜日期默认问题
          setTimeout(() => {
            this.getTableData();
          }, 300)
        }
      });
    } catch (error) {
      console.log(error)
      if (isQuery === 'Y') { // 自动查询标志
        this.setState({ spinLoading: false }, () => {
          setTimeout(() => {
            this.getTableData();
          }, 300)
        });
      }
    }
  }

  // 查询
  handleQuery = () => {
    this.setState({ page: 1 }, () => {
      this.getTableData('Y');
    })
  }

  // 获取列表数据
  getTableData = async (isClear) => {
    try {
      let { pageSize, page, categoryData } = this.state;
      if (!(categoryData && categoryData.queryCode)) {
        message.error('查询接口未配置，快去配置先！');
        return
      };
      let values = await this.queryFormRef.handleSave();
      if (values.error) {
        message.error('请完善必填信息');
        return;
      }
      this.setState({ loading: true });
      let patientInfo = this.patientRef && this.patientRef.getPatientInfo();
      let data = {
        params: [{
          ...values,
          ...patientInfo,
          recordPatNum: patientInfo?.patNo || '',
          status: categoryData?.groupType || undefined, // 界面标识
          groupType: categoryData?.groupType || undefined, // 界面标识
          compontName: categoryData?.componentName || undefined,
          componentName: categoryData?.componentName || undefined, // 组件名
        }],
        pagination: [{
          pageSize,
          currentPage: page
        }]
      }
      let res = await React.$asyncPost(this, categoryData.queryCode, data);
      let idIndex = categoryData?.idIndex || 'key';
      let tableData = Util.addKeyValueToDataSource(res.result && 'rows' in res.result ? res.result.rows : (Array.isArray(res.result) ? res.result : []), idIndex);
      if (categoryData && categoryData.totalStatistics) {
        this.state.totalStatistics = res.result[categoryData.totalStatistics];
      }
      this.setState({ tableData, total: res.result?.total || tableData.length, loading: false }, () => {
        isClear !== 'N' ? this.handleClearSelectData() : ''; // 清除操作数据
      });
    } catch (error) {
      console.log('错误', error)
      this.setState({ loading: false });
    }
  }

  // 清除操作数据
  handleClearSelectData = () => {
    this.setState({ rowID: '', rowData: {} });
  }

  // 分页操作
  compilePage = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getTableData('Y');
    })
  }

  // 操作行
  onClickRowPublic = (record) => {
    const { categoryData } = this.state;
    let idIndex = categoryData?.idIndex || 'id';
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== (record && idIndex in record ? record[idIndex] : record.key)))) {
          this.setState({ rowID: (record && idIndex in record ? record[idIndex] : record.key), rowData: record });
        } else {
          this.handleClearSelectData();
        }
      }
    }
  }

  // 选中行操作
  setRowClassNamePublic = (record) => {
    const { categoryData } = this.state;
    let idIndex = categoryData?.idIndex || 'id';
    let rowDataColorArr = categoryData && categoryData.rowDataColor ? categoryData.rowDataColor.split(',') : [];
    let colorExpression = '';
    for (let i = 0; i < rowDataColorArr.length; i++) {
      let currentItem = rowDataColorArr[i] && rowDataColorArr[i].indexOf('^') > -1 ? rowDataColorArr[i].split('^') : [];
      if (currentItem && currentItem.length > 2) {
        colorExpression += record[currentItem[0]] === currentItem[1] ? currentItem[2] : ''
      }
    }
    return (record && idIndex in record ? record[idIndex] : record.key) === this.state.rowID ? 'clickRowStyle' : colorExpression;
  }

  // 导出 
  handleExport = async () => {
    try {
      let { categoryData } = this.state;
      if (!(categoryData && categoryData.exportCode)) {
        message.error('查询接口未配置，快去配置先！');
        return
      };
      let values = await this.queryFormRef.handleSave();
      if (values.error) {
        message.error('请完善必填信息');
        return;
      }
      this.setState({ exportLoading: true });
      let patientInfo = this.patientRef && this.patientRef.getPatientInfo();
      let data = {
        params: [{
          ...values,
          ...patientInfo,
          recordPatNum: patientInfo?.patNo || '',
          status: categoryData?.groupType || undefined, // 界面标识
          groupType: categoryData?.groupType || undefined, // 界面标识
          compontName: categoryData?.componentName || undefined,
          componentName: categoryData?.componentName || undefined, // 组件名
        }]
      }
      let res = await React.$asyncPost(this, categoryData.exportCode, data);
      handleExcel.downloadExcel(res.result);
      this.setState({ exportLoading: false });
    } catch (error) {
      this.setState({ exportLoading: false });
    }
  }

  // 查询订单
  handleOrdersQuery = (record, e) => {

  }

  // 重置
  handleReset = () => {
    this.queryFormRef && this.queryFormRef.resetFields();
    this.patientRef && this.patientRef.resetFields();
    this.setState({ rowID: '', rowData: {}, tableData: [], total: 0, page: 1 });
  }

  // 查看详情
  handleViewDetails = (record, e) => {
    React.$stopPropagation(e);
    const { categoryData, rowData } = this.state;
    this.matchingDetailsRef && this.matchingDetailsRef.modifyVisible(true, { ...record, suppFlag: categoryData?.componentName || '', statusCode: rowData?.statusCode });
  }

  render() {
    const { categoryData, queryFormData, selectData, page, total, loading, tableData, totalWidth, columns, spinLoading, exportLoading, totalStatistics
    } = this.state;

    let operationCount = (categoryData?.operationViewDetailsFlag === 'Y' ? 1 : 0)
    // 列表操作
    const operationObj = {
      width: operationCount * 80 + 20,
      title: '操作',
      align: 'center',
      fixed: categoryData?.operationFixedFlag === 'Y' ? 'right' : null,
      key: 'operation',
      render: (text, record) => (
        <>
          {categoryData?.operationViewDetailsFlag === 'Y' ? (
            <Button
              type="link"
              disabled={!(record?.glassesRequestID || record?.requestID)}
              onClick={(e) => this.handleViewDetails(record, e)}
            >
              {categoryData?.viewDetailsBtnTitle || '查看详情'}
            </Button>
          ) : ''}
        </>
      ),
    };

    return (
      <Spin tip="正在初始化界面数据……" spinning={spinLoading}>
        <Row className="dynamic-component left-condition-right-list">
          <Col span={5}>
            <div style={{ paddingRight: '6px', position: 'relative', height: '100%' }}>
              <Card
                size="small"
                bordered={false}
                bodyStyle={{ paddingRight: '16px' }}
                title={(
                  <div className="card-title-left-img">
                    <img src={iconListvisits} alt="" />
                    {categoryData?.cardTitle || '搜索条件'}
                  </div>
                )}
              >
                <div className="scroll-bar-style" style={{ height: store.getState().tableHeight.y + 182 + 'px', overflow: 'auto', paddingTop: '4px' }}>
                  {categoryData?.queryPatInfoFlag === 'Y' ? (
                    <GetPatientInformation
                      isEnter="Y"
                      enterMargin="14px 0"
                      patWidth="75%"
                      parLabelClass="lcrl-input-label"
                      queryType="fuzzySearch"
                      cardType={selectData?.defaultValue?.defaultCardType || undefined}
                      cardSelectData={selectData?.cardType || []}
                      onRef={ref => this.patientRef = ref}
                      handleQuery={this.handleQuery}
                    />
                  ) : ''}
                  <DynamicRenderingForm
                    className="dynamic-component-form"
                    onRef={ref => this.queryFormRef = ref}
                    rowData={{}}
                    selectData={selectData}
                    formData={queryFormData && queryFormData.length > 0 && [...queryFormData].map((item => {
                      return {
                        ...item,
                        onPressEnter: item.typeCode === 'Input' || item.typeCode === 'InputNumber' || item.typeCode === 'TextArea' ? this.handleQuery : ''
                      }
                    }))}
                  />
                  <div style={{ textAlign: 'center', marginTop: '6px' }}>
                    {categoryData.exportCode ? (
                      <Button ghost style={{ marginRight: '20px' }} type="primary" onClick={this.handleExport} loading={exportLoading}>{categoryData?.exportBtnTitle || '导出'}</Button>
                    ) : (
                      <Button style={{ marginRight: '20px' }} onClick={this.handleReset}>清空</Button>
                    )}
                    <Button type="primary" onClick={this.handleQuery}>查询</Button>
                  </div>
                </div>
              </Card>
              <div className="common-card-right-split-line" style={{ width: 8 }}></div>
            </div>
          </Col>
          <Col span={19}>
            <Card
              size="small"
              bordered={false}
              title={(
                <div className="flex-align-items">
                  <div className="card-title-left-img">
                    <img src={iconMessages} alt="" />
                    {categoryData?.rightCardTitle || '查询列表'}
                  </div>
                  <div style={{ marginLeft: '56px' }}>
                    {totalStatistics && Array.isArray(totalStatistics) ? (
                      <div style={{ color: '#666' }} className="flex-align-items">
                        {totalStatistics.map((item, index) => {
                          return (
                            <div key={index}>
                              {item.title}
                              {item?.firstSplit || ' '}
                              <span style={{ marginRight: index === 0 ? '12px' : '20px', color: categoryData?.statisticsValueColor || '#007AFF', fontWeight: '700', fontSize: '14px' }}>
                                {item.value}
                                {item?.lastSplit || ''}
                              </span>
                            </div>
                          )
                        })}
                      </div>
                    ) : <span>{totalStatistics}</span>}
                  </div>
                </div>
              )}
              extra={(
                categoryData && categoryData.rowDataTitle ? (
                  <div className="flex-align-items">
                    {categoryData.rowDataTitle.split(',').map(((item, index) => {
                      let childData = item && item.indexOf('^') > -1 ? item.split('^') : [];
                      return (
                        <div className="flex-align-items" key={index} style={{ marginRight: '12px' }}>
                          <span style={{ display: 'inline-block', width: '16px', height: '16px', marginRight: '6px', background: childData && childData.length > 1 ? childData[1] : '#b9eddf', borderRadius: '2px' }}></span>
                          {childData && childData.length > 0 ? childData[0] : ''}
                        </div>
                      )
                    }))}
                  </div>
                ) : ''
              )}
            >
              <div className="table-body-height">
                <PublicTablePagination
                  param={{
                    page,
                    total,
                    loading,
                    size: categoryData?.paginationSize || 'large',
                    pageSize: categoryData?.defaultPageSize || '',
                    componentName: categoryData?.componentName || '',
                    data: tableData, // 表格数据
                    x: totalWidth, // 表格的宽度
                    y: store.getState().tableHeight.y + 94,
                    height: store.getState().tableHeight.y + 144,
                    columns: operationCount > 0 ? [...columns, operationObj] : columns, // 表头配置
                  }}
                  compilePage={this.compilePage}
                  getColumns={this.getTableColumns}
                  onClickRowPublic={this.onClickRowPublic}
                  setRowClassNamePublic={this.setRowClassNamePublic}
                />
              </div>
            </Card>
          </Col>
        </Row>

        {/* 查看详情 */}
        < MatchingDetails interfaceFlag="LeftConditionRightList" onRef={ref => this.matchingDetailsRef = ref} />
      </Spin>
    )
  }
};

export default LeftConditionRightList;